<?php

namespace App\Models\Admin;

use App\Models\BaseModel;
use Config, DB, Auth;
use App\Models\Admin\User;
use App\Models\Admin\Good;
use App\Models\Admin\Store;
use App\Models\Admin\OrderItem;
use App\Models\Admin\TeamAward;
use App\Exports\DealRecordExport;
use App\Exports\TeamMonthExport;
use App\Exports\FlhExport;
use Excel;
use App\Models\Admin\TotalBonusPool;

class DealRecord extends BaseModel
{
    protected $fillable = [
        'id', 'store_id', 'user_id', 'amount', 'type', 'status',
        'reason', 'deal_type', 'last_balance', 'new_balance', 
        'deal_item_id', 'order_type', 'jm_type', 'grade', 'mark', 
        'created_at', 'updated_at'
    ];
    // [余额]扣款
    public function deductMoney($goldRecord,$type=0){
        $goldRecord['type'] = 'out';
        $record = $this->changeInfo($goldRecord,$type);
        if ($record['code'] != 20000 ) {
            return $record;
        }
        
        DB::beginTransaction();
        try {
            $insert = $this->insert($record['data']);
            if ($insert && $record['data']['status'] == 1) {
                if($type == 0){//用户表余额回款
                    $keyYu = $this->getYu($record['data']['jm_type']);
                    $decrement = User::where('id', $record['data']['user_id'])->decrement($keyYu, $record['data']['amount']);//余额生效 出
                }else{//总奖金池表 各项奖金池回款
                    $key = $this->getBonusKey($type);
                    $decrement = TotalBonusPool::where('store_id',$record['data']['store_id'])->decrement($key, $record['data']['amount']);//余额生效 出
                }
                if ($decrement) {
                    DB::commit();
                    return $this->successClient($record, '[扣除]已生效交易记录生成成功!'); 
                } else {
                    return $this->errorClient($record, '[扣除]已生效交易记录生成失败!');
                }
            } else {
                DB::commit();
                return $this->successClient($record, '[扣除]未生效交易记录生成成功!'); 
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }
    // [余额]回款
    public function returnedMoney($goldRecord,$type=0){
        $goldRecord['type'] = 'in';
        $record = $this->changeInfo($goldRecord,$type);
        if ($record['code'] != 20000 ) {
            return $this->errorClient($goldRecord, '扣款数据不合法');
        }
        DB::beginTransaction();
        try {
            $insert = $this->insert($record['data']);
            if ($insert && $record['data']['status'] == 3) {
                if($type == 0){//用户表余额回款
                    $keyYu = $this->getYu($record['data']['jm_type']);
                    $increment = User::where('id',$record['data']['user_id'])->increment($keyYu, $record['data']['amount']);//余额生效 进
                }else{//总奖金池表 各项奖金池回款
                    $key = $this->getBonusKey($type);
                    $increment = TotalBonusPool::where('store_id',$record['data']['store_id'])->increment($key, $record['data']['amount']);//余额生效 进
                }
                if ($increment) {
                    DB::commit();
                    return $this->successClient($record, '[回款]已生效交易记录生成成功!'); 
                } else {
                    return $this->errorClient($record, '[回款]已生效交易记录生成失败!'.$increment);
                }
            } else {
                DB::commit();
                return $this->successClient($record, '[回款]未生效交易记录生成成功!'); 
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    // 金额 / 积分 / 军功章 统一逻辑
    private function changeInfo($goldRecord,$type=0)
    {
        $record=[];
        $record['type'] = $goldRecord['type'];
        $record['store_id'] = $goldRecord['store_id'];
        $record['user_id'] = $goldRecord['user_id'];
        $record['status'] = $goldRecord['status'];
        $record['reason'] = $goldRecord['reason'];
        $record['deal_type'] = $goldRecord['deal_type'];
        $record['deal_item_id'] = $goldRecord['deal_item_id'];
        $record['deal_user_id'] = isset($goldRecord['deal_user_id']) ? $goldRecord['deal_user_id'] : 0;
        $record['deal_get_id'] = isset($goldRecord['deal_get_id']) ? $goldRecord['deal_get_id'] : 0;
        $record['partner_time'] = isset($goldRecord['partner_time']) ? $goldRecord['partner_time'] : NULL;
        $record['order_type'] = $goldRecord['order_type'];
        $record['jm_type'] = $goldRecord['jm_type'];
        $record['grade'] = $goldRecord['grade'];
        $record['mark'] = isset($goldRecord['mark']) ? $goldRecord['mark'] : '';
        $record['amount'] = $goldRecord['amount'];
        $record['created_at'] = date('Y-m-d H:i:s');
        
        if (!isset($goldRecord['last_balance'])) {
            if($type == 0){
                $userInfo = User::where('id', $goldRecord['user_id'])->select('gold', 'jf', 'jgz','bd_index')->first();
                $keyYu = $this->getYu($goldRecord['jm_type']);
                $record['last_balance'] = $userInfo[$keyYu];
            }else{
                $total = TotalBonusPool::where('store_id', $goldRecord['store_id'])->first();
                $key = $this->getBonusKey($type);
                $record['last_balance'] = $total[$key];
            }
        } else {
            $record['last_balance'] = $goldRecord['last_balance'];
        }
        $record['new_balance'] = $record['type'] == 'in' ? $record['last_balance'] + $record['amount'] : $record['last_balance'] - $record['amount'];
        if ($record['new_balance'] < 0) {
            return $this->errorClient($record, '[失败:'.$goldRecord['jm_type'].']交易后余额为负!');
        } else {
            return $this->successClient($record, '交易记录数据准备成功!'); 
        }
    }
    public function getYu($jm_type)
    {
        $str = '';
        switch ($jm_type) {
            case 1:
                $str = 'gold';
                break;
            case 2:
                $str = 'jf';
                break;
            case 3:
                $str = 'jgz';
                break; 
            case 4:
                $str = 'bd_index';
                break;          
            default:
                # code...
                break;
        }
        return $str;
    }

    public function getList($pageSize, $requestStoreId, $userId, $dealItemId, $goldType, $begin_at, $end_at, $grade, $deal_type, $status, $recharge_type, $report)
    {
        $storeId = Auth::guard('admin')->user()->store_id;
        $teamAward = new TeamAward;
        $awardName = '富利指数';
        $bdAwardName = '报单指数';
        
        $sql = $this;
        // $sql = $sql->where('user_id', '!=', 1);
        if(!empty($dealItemId)) {
            $sql = $sql->where('deal_item_id', $dealItemId);
        }
        if(!empty($userId)) {
            $sql = $sql->where('user_id', $userId);
        }
        if(!empty($goldType)) {
            $sql = $sql->where('jm_type', $goldType);
        }
        if($grade != '') {
            $sql = $sql->where('grade', $grade);
        }
        if($deal_type != '') {
            $deal_type = $this->dealTypeItem($deal_type);
            $sql = $sql->whereIn('deal_type', $deal_type);
        }
        if($status != ''){
            $sql = in_array($status,[1,3]) ? $sql->whereIn('status',[1,3]) : $sql->whereIn('status',[0,2]);
        }
        if($recharge_type != '') {
            $sql = $sql->where('deal_type', $recharge_type);
        }
        if(date('Y-m-d H:i:s',strtotime($begin_at)) == $begin_at && date('Y-m-d H:i:s',strtotime($end_at)) == $end_at){
            $sql = $sql->whereBetween('created_at', [$begin_at,$end_at]);
        }
        if ($storeId == 0) {
            // 管理员查看全部店铺交易记录 按店铺排序
            if ($requestStoreId == 0) {
                $sql = $sql->orderBy('store_id', 'desc')->orderBy('created_at', 'desc')->orderBy('id', 'desc');
            } else {
                $sql = $sql->where('store_id', $requestStoreId)->orderBy('created_at', 'desc')->orderBy('id', 'desc');
                $team = $teamAward->awardGold($requestStoreId);
                $awardName = $team->award_name;
                $bdAwardName = $team->bd_award_name;
                $storeId = $requestStoreId;
            }
        } else {
            // 店家只能查看自己店的交易记录
            $sql = $sql->where('store_id', $storeId)->orderBy('created_at', 'desc');
            $team = $teamAward->awardGold($storeId);
            $awardName = $team->award_name;
            $bdAwardName = $team->bd_award_name;
        }

        if(!empty($report)) {
            ini_set("max_execution_time",300);
            ini_set('memory_limit','2048M');
            $data = $sql->get()->toArray();
            $data = $this->handleImportOrderData($data);
            return Excel::download(new DealRecordExport($data), '对账记录'.date('Y-m-d').'.xlsx');
        }

        $data = $sql->paginate($pageSize)->toArray();
        $data = $this->handleData($data);
        $data['awardName'] = $awardName;
        $data['bdAwardName'] = $bdAwardName;
        $data['deal_type_list'] = [
            1 => '会员折扣',
            2 => '团购折让',
            3 => '富利惠',
            4 => '百乐惠',
            5 => '教育培训基金',
            6 => '码上返',
            7 => '报单公积',
            8 => '虹包',
            9 => '分虹',
            107 => '分享经济',
            19 => '店铺回款',
            130 => '分享经济转入会员折扣',
            106 => '会员余额支付订单',
            141 => '会员直接支付订单',
        ];
        $data['recharge_type'] = [
            1 => '微信充值',
            2 => '银行卡充值',
            3 => '后台充值',
            4 => '提现',
        ];

        return $this->success($data);
    }

    private function handleImportOrderData($data)
    {
        $arr = [];
        //$orderids = array_column($data,'deal_item_id');
        //$orderItem = new OrderItem;
        //$order = $orderItem->whereIn('order_id',$orderids)->select('order_id','pay_price','good_title','goods_quantity','good_describe')->get()->toArray();
        
        $userIds = array_column($data,'user_id');
        $userInfo = User::whereIn('id',$userIds)->select('id','nickname','store_id')->get()->toArray();

        $store_ids = array_column($data,'store_id');
        $grade = Grade::whereIn('store_id',$store_ids)->get()->toArray();

        foreach ($data as $k => $deal) {
            $data[$k]['nickname'] = '';
            $data[$k]['grade_title'] = '';
            foreach ($userInfo as $key => $value) {
                if($deal['user_id'] == $value['id']){
                    $data[$k]['nickname'] = $value['nickname'];
                }
            }

            foreach ($grade as $g => $r) {
                if($deal['store_id'] == $r['store_id'] && $deal['grade'] == $r['level']){
                    $data[$k]['grade_title'] = $r['title'];
                }
            }
        }
        $orderItem = new OrderItem;
        foreach($data as $k => $deal) {
            $item = [];
            $order = $orderItem->where('order_id',$deal['deal_item_id'])->select('order_id','pay_price','good_title','goods_quantity','good_describe')->get()->toArray();
            if(empty($order)){
                $item['created_at'] = $deal['created_at'];
                $item['id'] = $deal['id'];
                $item['store_id'] = $deal['store_id'];
                $item['user_id'] = $deal['user_id'];
                $item['nickname'] = $deal['id'] == 1 ? '公司' : $deal['nickname'];
                $item['grade'] = $deal['id'] == 1 ? '公司' : $deal['grade_title'];
                $item['type'] = $deal['type'] == 'in' ? '增加' : '减少';
                $item['amount'] = $deal['amount'] / 100;
                $item['last_balance'] = $deal['last_balance'] / 100;
                $item['new_balance'] = $deal['new_balance'] / 100;
                $item['reason'] = $deal['reason'];
                $item['status'] = ($deal['status'] == 1 || $deal['status'] == 3) ? '已生效' : '未生效';
                $item['deal_item_id'] = $deal['deal_item_id'];
                $item['good_title'] = '';
                $item['good_num'] = '';
                $item['good_price'] = '';
                $item['pay_orderid'] = $deal['pay_orderid'];
                $item['deal_get_id'] = $deal['deal_get_id'];
                $item['partner_at'] = $deal['partner_time'];
                $item['order_type'] = $this->orderType($deal['order_type'],$deal['store_id']);
                $item['jm_type'] = $this->jmType($deal['jm_type'],$deal['store_id']);
                $item['mark'] = $deal['mark'];
                array_push($arr, $item);
            }else{
                foreach ($order as $key => $value) {
                    $item['created_at'] = $deal['created_at'];
                    $item['id'] = $deal['id'];
                    $item['store_id'] = $deal['store_id'];
                    $item['user_id'] = $deal['user_id'];
                    $item['nickname'] = $deal['id'] == 1 ? '公司' : $deal['nickname'];
                    $item['grade'] = $deal['id'] == 1 ? '公司' : $deal['grade_title'];
                    $item['type'] = $deal['type'] == 'in' ? '增加' : '减少';
                    $item['amount'] = $deal['amount'] / 100;
                    $item['last_balance'] = $deal['last_balance'] / 100;
                    $item['new_balance'] = $deal['new_balance'] / 100;
                    $item['reason'] = $deal['reason'];
                    $item['status'] = ($deal['status'] == 1 || $deal['status'] == 3) ? '已生效' : '未生效';
                    $item['deal_item_id'] = $deal['deal_item_id'];
                    $item['good_title'] = $value['good_title'].'('.$value['good_describe'].')';
                    $item['good_num'] = $value['goods_quantity'];
                    $item['good_price'] = $value['pay_price']/100;
                    $item['pay_orderid'] = $deal['pay_orderid'];
                    $item['deal_get_id'] = $deal['deal_get_id'];
                    $item['partner_at'] = $deal['partner_time'];
                    $item['order_type'] = $this->orderType($deal['order_type'],$deal['store_id']);
                    $item['jm_type'] = $this->jmType($deal['jm_type'],$deal['store_id']);
                    $item['mark'] = $deal['mark'];
                    array_push($arr, $item);
                }    
            }
            
        }

        // foreach($data as $k => $deal) {
        //     foreach ($order as $key => $value) {
            
        //     $user = User::where('id', $deal['user_id'])->first();
        //     $item = [];
        //     $item['id'] = $deal['id'];
        //     $item['store_id'] = $deal['store_id'];
        //     $item['user_id'] = $deal['user_id'];
        //     $item['nickname'] = $user->id == 1 ? '公司' : $user->nickname;
        //     $item['grade'] = $user->id == 1 ? '公司' : Grade::where('store_id', $user->store_id)->where('level', $deal['grade'])->first()->title;
        //     $item['type'] = $deal['type'] == 'in' ? '增加' : '减少';
        //     $item['amount'] = $deal['amount'] / 100;
        //     $item['last_balance'] = $deal['last_balance'] / 100;
        //     $item['new_balance'] = $deal['new_balance'] / 100;
        //     $item['reason'] = $deal['reason'];
        //     $item['status'] = ($deal['status'] == 1 || $deal['status'] == 3) ? '已生效' : '未生效';
        //     $item['deal_item_id'] = $deal['deal_item_id'];
        //     $item['good_title'] = $value['good_title'].'('.$value['good_describe'].')';
        //     $item['good_num'] = $value['goods_quantity'];
        //     $item['good_price'] = $value['pay_price'];
        //     $item['pay_orderid'] = $deal['pay_orderid'];
        //     $item['deal_get_id'] = $deal['deal_get_id'];
        //     $item['partner_at'] = $deal['partner_time'];
        //     $item['order_type'] = $this->orderType($deal['order_type'],$user->store_id);
        //     $item['jm_type'] = $this->jmType($deal['jm_type'],$user->store_id);
        //     $item['mark'] = $deal['mark'];
        //     $item['created_at'] = $deal['created_at'];
        //     array_push($arr, $item);
        //     }
        // }
        return $arr;
    }

    private function handleData($data)
    {
        foreach ($data['data'] as $k => $item) {
            $user = User::where('id', $item['user_id'])->first();
            $data['data'][$k]['nickname'] = $user->id == 1 ? '公司' : $user->nickname;
            $data['data'][$k]['amount'] = $item['amount'] / 100;
            $data['data'][$k]['last_balance'] = $item['last_balance'] / 100;
            $data['data'][$k]['new_balance'] = $item['new_balance'] / 100;
            $data['data'][$k]['jgz'] = $user->jgz / 100;
            $data['data'][$k]['grade'] = $user->id == 1 ? '公司' : Grade::where('store_id', $user->store_id)->where('level', $item['grade'])->first()->title;
            $data['data'][$k]['order_type'] = $this->orderType($item['order_type'],$user->store_id);
            $data['data'][$k]['jm_type'] = $this->jmType($item['jm_type'],$user->store_id);
            $data['data'][$k]['partner_at'] = $item['partner_time'];
        }

        return $data;
    }

    private function orderType($value,$store_id = 0)
    {   
        if($store_id == 0){
            $awardName = '富利指数';
        }else{
            $teamAward = new TeamAward;
            $team = $teamAward->awardGold($store_id);
            $awardName = $team->award_name;
        }
        switch ($value) {
            case 1:
                return "充值";
            case 2:
                return "提现";
            case 3:
                return "会员订单";
            case 4:
                return "后台发放";
            case 5:
                return $awardName."转化余额";
            case 6:
                return "转账";
        }
        return "";
    }

    private function jmType($value,$store_id)
    {   
        if($store_id == 0){
            $awardName = '富利指数';
        }else{
            $teamAward = new TeamAward;
            $team = $teamAward->awardGold($store_id);
            $awardName = $team->award_name;
            $bdAwardName = $team->bd_award_name;
        }
        switch ($value) {
            case 1:
                return "余额";
            case 2:
                return "积分";
            case 3:
                return $awardName;
            case 4:
                return $bdAwardName;
        }
        return "";
    }

    public function getBonusKey($type){
        $str = '';
        switch ($type) {
            case 1:
                $str = 'bonus_pool_one_sum';
                break;
            case 2:
                $str = 'team_month_sum';
                break;
            case 3:
                $str = 'team_year_sum';
                break; 
            case 4:
                $str = 'team_recommend_sum';
                break; 
            case 5:
                $str = 'team_fund_sum';
                break;  
            case 6:
                $str = 'bd_referrer_sum';//直推池子
                break;
            case 7:
                $str = 'bd_provident_fund_sum';//报单公积 没有直推，间推（推荐用户及合伙人）都是进此池子
                break;
            case 8:
                $str = 'bd_member_pool_sum';//虹包
                break;   
            case 9:
                $str = 'bd_order_pool_sum';//分虹
                break;               
            default:
                # code...
                break;
        }
        return $str;
    }
    public function getAmountSum($store_id,$deal_type,$beg,$end){
        return $this->where('store_id',$store_id)->where('deal_type',$deal_type)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end])->sum('amount');
    }

    public function userAmountSum($store_id,$deal_type,$beg,$end){
        return $this->where('store_id',$store_id)->where('deal_type',$deal_type)->where('status',3)->where('is_set',0)
        ->where('deal_records.deal_get_id','!=',0)
        ->whereBetween('created_at',[$beg, $end])
        ->get()->toArray();
    }

    public function teamData($userMonth,$userRecommend){
        $data = [];
        foreach ($userMonth as $key => $value) {
           if(!isset($data[$value['deal_get_id']])){
               $data[$value['deal_get_id']]['store_id'] = $value['store_id'];
               $data[$value['deal_get_id']]['user_id'] = $value['deal_get_id'];
               $data[$value['deal_get_id']]['month'] = $value['amount'];
               $data[$value['deal_get_id']]['recommend'] = 0;
           }else{
               $data[$value['deal_get_id']]['month'] += (int)$value['amount'];
           }   
        }

        foreach ($userRecommend as $key => $value) {
           if(!isset($data[$value['deal_get_id']])){
               $data[$value['deal_get_id']]['store_id'] = $value['store_id'];
               $data[$value['deal_get_id']]['user_id'] = $value['deal_get_id'];
               $data[$value['deal_get_id']]['month'] = 0;
               $data[$value['deal_get_id']]['recommend'] = $value['amount'];                
            }else{
               $data[$value['deal_get_id']]['recommend'] += (int)$value['amount'];
           }   
        }
        return $data;
    }

    public function teamMonthSend($store_id){
        $user = new User;
        $pool = new TotalBonusPool;
        $beg = date('Y-m-1 00:00:00',strtotime('last month'));
        $end = date('Y-m-d 23:59:59',strtotime(date('Y-m-1').'-1 day'));

         //获取每个用户生成的月度合伙人总奖金
         $userMonth = $this->userAmountSum($store_id,22,$beg,$end);
         $userRecommend = $this->userAmountSum($store_id,24,$beg,$end);

         $data = array_values($this->teamData($userMonth,$userRecommend));
        
         $userIds = array_column($data,'user_id');
        
         $info = $user->whereIn('id',$userIds)->select('id','grade','gold')->get()->toarray();

         $monthlist = $this->where('store_id',$store_id)->where('deal_type',22)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end])->get()->toArray();
         $recommendlist = $this->where('store_id',$store_id)->where('deal_type',24)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end])->get()->toArray();
         $mIds = array_column($monthlist,'id');
         $rIds = array_column($recommendlist,'id');
         $dealIds = array_unique(array_merge($mIds,$rIds));

         $arr = [];
         $month = [];
         $recom = [];
         $monthSum = 0;
         $recomSum = 0;
         $monthDeduct = [];
         $recomDeduct = [];

         $list = [];
         foreach($data as $key => $value){
            foreach ($info as $k => $v) {
                $arr['store_id'] = $store_id;
                $arr['status'] = 3;
                $arr['type'] = 'in';
                $arr['deal_item_id'] = '';
                $arr['order_type'] = 3;// 会员订单
                $arr['jm_type'] = 1;// 余额
                $arr['mark'] = '';
                $arr['created_at'] = date('Y-m-d H:i:s');// 月度奖金池金额扣除
                
                if($value['user_id'] == $v['id']){
                    if($value['month'] > 0){
                        $monthSum += $value['month'];
                        $arr['reason'] = '团购折让发放';
                        $arr['deal_type'] = 31;// 月度奖金池金额扣除
                        $arr['user_id'] = $value['user_id'];//奖金池收入 不更新用户表余额
                        $arr['grade'] = $v['grade'];
                        $arr['amount'] = $value['month'];
                        $arr['last_balance'] = $v['gold'];// 月度奖金池金额扣除
                        $new_balance = $v['gold'] + $value['month'];
                        $arr['new_balance'] = $new_balance;// 月度奖金池金额扣除
                        array_push($month,$arr);
                    }

                    if($value['recommend'] > 0){
                        $recomSum += $value['recommend'];
                        $arr['reason'] = '百乐惠发放';
                        $arr['deal_type'] = 32;// 月度奖金池金额扣除
                        $arr['user_id'] = $value['user_id'];//奖金池收入 不更新用户表余额
                        $arr['grade'] = $v['grade'];
                        $arr['amount'] = $value['recommend'];
                        $arr['last_balance'] = $value['month'] > 0 ? $new_balance : $v['gold'];//isset($new_balance) ? $new_balance : $v['gold'];// 月度奖金池金额扣除
                        $new_balance = $value['month'] > 0 ? $new_balance + $value['recommend'] : $v['gold'] + $value['recommend'];
                        $arr['new_balance'] = $new_balance;// 月度奖金池金额扣除
                        array_push($recom,$arr);
                    }

                    $list[] = [
                        'id' => $value['user_id'],
                        'gold' => $new_balance
                    ];
                }
                
            }

         }
         
        DB::beginTransaction();
        try {
            $this->insert($month);
            $this->insert($recom);
            
            $this->updateBatch('users',$list);

            if($monthSum > 0){
                $monthDeduct['store_id'] = $store_id;
                $monthDeduct['status'] = 1;
                $monthDeduct['deal_item_id'] = '';
                $monthDeduct['order_type'] = 3;// 会员订单
                $monthDeduct['jm_type'] = 1;// 余额
                $monthDeduct['user_id'] = 1;//奖金池收入 不更新用户表余额
                $monthDeduct['grade'] = 0;
                $monthDeduct['mark'] = date('Ymd').'团购折让结算,发放当月累计金额';
                $monthDeduct['amount'] = $monthSum;
                $monthDeduct['reason'] = '团购折让结算';
                $monthDeduct['deal_type'] = 27;// 月度奖金池金额扣除

                $monthResult = $this->deductMoney($monthDeduct, 2);
                if ($monthResult['code'] != 20000) {
                    return $monthResult;
                }
            }

            if($recomSum > 0){
                $recomDeduct['store_id'] = $store_id;
                $recomDeduct['status'] = 1;
                $recomDeduct['deal_item_id'] = '';
                $recomDeduct['order_type'] = 3;// 会员订单
                $recomDeduct['jm_type'] = 1;// 余额
                $recomDeduct['user_id'] = 1;//奖金池收入 不更新用户表余额
                $recomDeduct['grade'] = 0;
                $recomDeduct['mark'] = date('Ymd').'百乐惠结算,发放当月累计金额';
                $recomDeduct['amount'] = $recomSum;
                $recomDeduct['reason'] = '百乐惠结算';
                $recomDeduct['deal_type'] = 29;// 月度奖金池金额扣除
                $recomResult = $this->deductMoney($recomDeduct, 4);
                if ($recomResult['code'] != 20000) {
                    return $recomResult;
                }
            }   
            $this->whereIn('id',$dealIds)->update(['is_set'=>1]);
            DB::commit();
            return $this->successClient($list,'团购折让发放成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    public function updateBatch($tableName = "", $multipleData = array()){  
  
        if( $tableName && !empty($multipleData) ) {  
  
            // column or fields to update  
            $updateColumn = array_keys($multipleData[0]);  
            $referenceColumn = $updateColumn[0]; 
            unset($updateColumn[0]);  
            $whereIn = "";  
  
            $q = "UPDATE ".$tableName." SET ";   
            foreach ( $updateColumn as $uColumn ) {  
                $q .=  $uColumn." = CASE ";  
  
                foreach( $multipleData as $data ) {  
                    $q .= "WHEN ".$referenceColumn." = ".$data[$referenceColumn]." THEN '".$data[$uColumn]."' ";  
                }  
                $q .= "ELSE ".$uColumn." END, ";  
            }  
            foreach( $multipleData as $data ) {  
                $whereIn .= "'".$data[$referenceColumn]."', ";  
            }  
            $q = rtrim($q, ", ")." WHERE ".$referenceColumn." IN (".  rtrim($whereIn, ', ').")";  
  
            // Update    
            return DB::update(DB::raw($q));  
  
        } else {  
            return false;  
        }  
  
    } 

    public function handleImportTeamMonthData($store_id,$beg,$end){
        $arr = [];
        $record = $this->join('order_items as i','deal_records.deal_item_id','=','i.order_id')
                ->whereIn('deal_type',[22,24])
                ->where('deal_records.store_id',$store_id)
                ->where('deal_records.status',3)
                ->where('deal_records.order_type',3)
                ->where('deal_records.is_set',0)
                ->whereBetween('deal_records.created_at',[$beg, $end])
                ->get()->toArray();
            
        $goods = Good::where('store_id',$store_id)->orderBy('id',"asc")->get()->toArray();
        $title = ['获得人','订单ID','下单人','描述','预计发放','实际发放'];
        foreach ($goods as $key => $value) {
            array_push($title,$value['title']);
                
        }
            foreach ($record as $key => $value) {
                    $k = $value['order_id'].'-'.$value['deal_type'];
                    if(isset($arr[$k])){
                        $arr[$k][$value['good_id']] += $value['goods_quantity'];
                    }else{
                        $arr[$k]['user_id'] = $value['deal_get_id'] == 0 ? '公司' : $value['deal_get_id'];
                        $arr[$k]['deal_item_id'] = $value['deal_item_id'];
                        $arr[$k]['deal_user_id'] = $value['deal_user_id'];
                        $arr[$k]['reason'] = $value['reason'];
                        $arr[$k]['amount'] = $value['amount']/100;
                        $arr[$k]['real'] = $value['deal_get_id'] > 0 ? $value['amount']/100 : 0;
                        foreach ($goods as $key1 => $v) {
                            $field = $v['id'];
                            if($value['good_id'] == $v['id']){
                                $arr[$k][$field] = $value['goods_quantity'];
                            }else{
                                $arr[$k][$field] = 0;
                            }
                        }
                    }
            }
        return Excel::download(new TeamMonthExport($arr,$title), 'team_month.xlsx');
    }

    public function handleImportBonusData($store_id,$type){
        $pool = new TotalBonusPool;
        $info = $pool->getBonusType($type);
        $ids = array_merge($info['in'],$info['out']);
        $data = $this->whereIn('deal_type',$ids)->where('store_id',$store_id)->whereIn('status',[1,3])->get()->toArray();
        
        $data = $this->handleImportOrderData($data);
        return Excel::download(new DealRecordExport($data), 'deal_record.xlsx');
    }

    public function surplusAmount($store_id,$type){
        $pool = new TotalBonusPool;
        $info = $pool->getBonusType($type);
        if(in_array($type,[1,2,3,4,8,9])){
            $in = $this->whereIn('deal_type',$info['in'])->where('store_id',$store_id)->where('status',3)->where('is_set',1)->sum('amount');
        }else{
            $in = $this->whereIn('deal_type',$info['in'])->where('store_id',$store_id)->where('status',3)->sum('amount');
        }
        $out = $this->whereIn('deal_type',$info['out'])->where('store_id',$store_id)->where('status',1)->sum('amount');
       
        return $surplus = ($in - $out)/100;
    }

    public function transfer($store_id,$type,$user_id=null,$reason=null,$num=0){
        DB::beginTransaction();
        try {
            $amount = $this->surplusAmount($store_id,$type);
            if($type == 5){
                if($num > $amount) return $this->errorClient(['info'=>'教育培训基金剩余金额不足！']);
                $amount = $num;
            }

            $pool = new TotalBonusPool;
            $info = $pool->getBonusType($type);
            $arr = [];
            $arr['store_id'] = $store_id;
            $arr['status'] = 1;
            $arr['deal_item_id'] = '';
            $arr['order_type'] = 3;// 会员订单
            $arr['jm_type'] = 1;// 余额
            $arr['user_id'] = 1;//奖金池交易 不更新用户表余额
            $arr['grade'] = 0;
            $arr['mark'] = '';
            $arr['amount'] = $amount*100;
            $arr['reason'] = $info['transfer_out_reason'];
            $arr['deal_type'] = $info['transfer_out_type'];
            $arrResult = $this->deductMoney($arr, $info['type']);
            if ($arrResult['code'] != 20000) {
                return $arrResult;
            }

            if($type == 5){
                $user = User::where('id',$user_id)->first();
                if(empty($user)) return $this->errorClient(['info'=>'请填写正确的用户ID']);
                $userArr = [];
                $userArr['store_id'] = $store_id;
                $userArr['status'] = 3;
                $userArr['deal_item_id'] = '';
                $userArr['order_type'] = 3;// 会员订单
                $userArr['jm_type'] = 1;// 余额
                $userArr['mark'] = date('Ymd').'教育培训基金转出';
                $userArr['reason'] = empty($reason) ? '教育培训基金发放' : $reason;
                $userArr['deal_type'] = 43;
                $userArr['user_id'] = $user_id;
                $userArr['grade'] = $user['grade'];
                $userArr['amount'] = $amount*100;
                $result = $this->returnedMoney($userArr);
                if ($result['code'] != 20000) {
                    return $result;
                }
            }else{
                $getInfo = $pool->getBonusType($info['transfer_to_id']);
                $in = [];
                $in['store_id'] = $store_id;
                $in['status'] = 3;
                $in['deal_item_id'] = '';
                $in['order_type'] = 3;// 会员订单
                $in['jm_type'] = 1;// 余额
                $in['user_id'] = 1;//奖金池交易 不更新用户表余额
                $in['grade'] = 0;
                $in['mark'] = '';
                $in['amount'] = $amount*100;
                $in['reason'] = $info['reason'].'剩余金额转入'.$getInfo['reason'];
                $in['deal_type'] = $getInfo['transfer_in_type'];
                $inResult = $this->returnedMoney($in, $getInfo['type']);
                if ($inResult['code'] != 20000) {
                    return $inResult;
                }
            }
            DB::commit();
            return $this->successClient($amount,'剩余金额转出成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    public function dealTypeItem($type){
        if($type <= 9){
            $pool = new TotalBonusPool;
            $info = $pool->getBonusType($type);
            $ids = array_merge($info['in'],$info['out']);
        }else if($type > 10 && $type < 99){
            $ids = [9,34];
        }else{
            $ids = [$type-100];
        }
        return $ids;
    }

    public function reviewAmount($request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $storeId = $request['storeId'];
            if (empty($storeId)) {
                return $this->error(['info' => '请输入店铺ID']);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $storeId = $user->store_id;
        }

        $user = new User;
        $userInfo = $user->where('phone','!=','')->where('password','!=','')->paginate($request->pageSize)->toArray();
        $userIds = array_column($userInfo['data'],'id');

        $type_list = [];
        $jm_type = $request->jm_type;
        if(empty($jm_type)){
            $jm_type = 1; 
        }
        $field = $this->getYu($jm_type);

        //余额增加的交易记录
        $goldIn = $this->whereIn('user_id',$userIds)->where('status',3)->whereNotIn('deal_type',[41])->where('jm_type',$jm_type)->groupby("user_id")->select("user_id",DB::raw('SUM(amount) as amountSum'))->get()->toArray();;
        //余额扣除的交易记录
        $goldOut = $this->whereIn('user_id',$userIds)->where('status',1)->whereNotIn('deal_type',[41])->where('jm_type',$jm_type)->groupby("user_id")->select("user_id",DB::raw('SUM(amount) as amountSum'))->get()->toArray();;
        
        //用户最后一条交易记录 交易后余额
        $goldLast=$this->whereIn("user_id",$userIds)->where('jm_type',$jm_type)->whereIn("status",[1,3])->select("user_id",DB::raw('MAX(id) as max_id'))->groupby("user_id")->get()->toArray();
        $maxIds = array_column($goldLast,'max_id');
        $lastRecord = $this->whereIn('id',$maxIds)->select('user_id','new_balance')->get()->toArray();

        $last = array_combine(array_column($lastRecord,'user_id'),$lastRecord);
        $in = array_combine(array_column($goldIn,'user_id'),$goldIn);
        $out = array_combine(array_column($goldOut,'user_id'),$goldOut);

        $store = new Store;
        $storeInfo = $store->findStore($storeId);

        $diffArr = [];
        foreach ($userInfo['data'] as $key => $value) { 
            $userInfo['data'][$key]["last"] = isset($last[$value['id']]['new_balance']) ? $last[$value['id']]['new_balance'] : 0;
            $userInfo['data'][$key]["out"] = isset($out[$value['id']]['amountSum']) ? $out[$value['id']]['amountSum'] : 0;
            $userInfo['data'][$key]["in"] = isset($in[$value['id']]['amountSum']) ? $in[$value['id']]['amountSum'] : 0;
            
            $userInfo['data'][$key]['end'] = (int)$userInfo['data'][$key]['in'] - (int)$userInfo['data'][$key]['out'];

            $userInfo['data'][$key]['title'] = $storeInfo['title'];

            $userInfo['data'][$key]['diff'] = $value[$field] == $userInfo['data'][$key]['end']&&$value[$field] == $userInfo['data'][$key]['last'] ? "无" : "有";

            if($userInfo['data'][$key]['diff'] == '有'){    
                $diffArr[] = $userInfo['data'][$key]; 
            }
        }

        if($request->question == 'question'){
            $userInfo['data'] = $diffArr;
            $userInfo['total'] = count($diffArr);
        }
        return $this->success($userInfo);
    }

    public function flhData($store_id){
        //去年的开始时间和结束时间
        $start = date("Y-01-01 00:00:00",strtotime('-1 years'));
        $end = date("Y-12-31 23:59:59",strtotime('-1 years'));
        
        $partners = User::where("is_partner",1)->get()->toArray();
        $partner_ids = array_column($partners,'id');
        
        $info = $this->join("users as u","deal_records.user_id","=","u.id")
            ->whereIn("user_id",$partner_ids)
            ->where("jm_type",3)
            ->where("type","in")
            ->whereRaw("deal_records.created_at >= '$start' and deal_records.created_at <= '$end'") //>= u.partner_at第一年计算成为合伙人后获取的富利指数
            ->groupBy('user_id')
            ->select("u.id","u.grade","u.partner_at","u.gold",DB::raw('SUM(deal_records.amount) as amount'))
            ->get()->toArray();
        if(empty($info)) return false;
        //去年成为合伙人后获取富力指数总数
        $amounts = array_sum(array_column($info,'amount'));
        //去年总富力惠
        $sum = $this->where("deal_type",23)->where("type","in")->whereBetween("created_at",[$start,$end])->where('is_set',0)->sum("amount");

        $num = ($sum/$amounts)*1000;
        //得出单个富力指数价值 保留小数点后三位
        if($num >= 1){
            $unit_price = floor($num)/1000;
        }else{
            $unit_price = 0;
        }

        //每人可获得金额明细 及 发放总金额
        $arr = [];
        $send_reward = 0;
        foreach ($info as $key => $value) {
            $self_jgz = $value['amount'] / 100;
            $arr[$key]['store_id'] = $store_id;//店铺ID
            $arr[$key]['id'] = $value['id'];//用户ID
            $arr[$key]['grade'] = '合伙人';//用户等级
            $arr[$key]['jgz'] = $self_jgz;//用户可结算富力指数
            $arr[$key]['reward'] = 0;//用户结算获取金额

            $self_reward = floor($self_jgz * $unit_price);
            if ($self_reward < 1) {
                continue;
            }
            $arr[$key]['reward'] = $self_reward;
            $send_reward += $self_reward;
        }
        $data = [];
        $data['arr'] = $arr;
        $data['sum'] = $sum;
        $data['amounts'] = $amounts;
        $data['unit_price'] = $unit_price;
        $data['send_reward'] = $send_reward;
        $data['unit_price'] = $unit_price;
        return $data;
    }

    public function flhList($store_id,$report){
        $result = $this->flhData($store_id);
        if(!$result) return $this->errorClient(['info' => '成为合伙人后截止到去年年底没有富力指数可结算!']);
        //当前帐号所属店铺 或者超管选择店铺 团队奖励名称
        if($store_id == 0){
            $awardName = '富利指数';
        }else{
            $teamAward = new TeamAward;
            $team = $teamAward->awardGold($store_id);
            $awardName = $team->award_name;
        }
        if(!empty($report)){
            return Excel::download(new FlhExport($result['arr']), date('Y-m-d').'富力惠列表.xlsx');
        }

        $data = [];
        $data['data'] = $result['arr'];// 每人数据
        $data['total'] = count($result['arr']);// 总人数
        $data['reward'] = $result['sum']/100;// 总奖金
        $data['jgz'] = $result['amounts']/100;// 总军功章
        $data['person_get'] = $result['unit_price'];// 军功章单价
        $data['send_reward'] = $result['send_reward'];// 放出的奖金, 与应发放奖金有一定的差值
        $data['awardName'] = $awardName;// 团队奖励名称
        $data['path'] = env('APP_URL').'/member/flh_list';
        return $this->success($data);
    }

    public function flhSend($store_id){
        $res = $this->whereIn('deal_type',[28,33])->whereBetween('created_at',[date('Y-01-01 00:00:00'),date('Y-12-31 23:59:59')])->get();
        if(count($res) > 0){
            return $this->errorClient(['info' => '富力惠已经结算过,明年再来吧!']);
        }
        $data = $this->flhData($store_id);
        if(!$data) return $this->errorClient(['info' => '成为合伙人后截止到去年年底没有富力指数可结算!']);
        //用户余额增加
        $arr = [];
        //富力惠扣减
        $deduct = [];
        DB::beginTransaction();
        try {
            foreach ($data['arr'] as $key => $value) {
                $arr['store_id'] = $store_id;
                $arr['status'] = 3;
                $arr['deal_item_id'] = '';
                $arr['order_type'] = 3;// 会员订单
                $arr['jm_type'] = 1;// 余额
                $arr['mark'] = date('Ymd').'富力惠结算';
                $arr['reason'] = '富力惠发放';
                $arr['deal_type'] = 33;
                $arr['user_id'] = $value['id'];
                $arr['grade'] = 2;
                $arr['amount'] = $value['reward']*100;
                $result = $this->returnedMoney($arr);
                if ($result['code'] != 20000) {
                    return $result;
                }
            }
            $deduct['store_id'] = $store_id;
            $deduct['status'] = 1;
            $deduct['deal_item_id'] = '';
            $deduct['order_type'] = 3;// 会员订单
            $deduct['jm_type'] = 1;// 余额
            $deduct['user_id'] = 1;//奖金池收入 不更新用户表余额
            $deduct['grade'] = 0;
            $deduct['mark'] = date('Ymd').'富力惠结算';
            $deduct['amount'] = $data['send_reward']*100;
            $deduct['reason'] = '富力惠结算';
            $deduct['deal_type'] = 28;
            $deductResult = $this->deductMoney($deduct, 3);
            if ($deductResult['code'] != 20000) {
                return $deductResult;
            }
            $this->where("deal_type",23)->where("type","in")->whereBetween("created_at",[date("Y-01-01 00:00:00",strtotime('-1 years')),date("Y-12-31 23:59:59",strtotime('-1 years'))])->update(['is_set'=>1]);
            DB::commit();
            return $this->successClient($data['arr'],'富力惠发放成功');
        } catch (\Exception $e) {
            DB::rollBack();
            return $e;
            return $e->getLine().$e->getMessage();
        }
    }
}
